<?php

namespace App\Ant\Excel\Imports;

use App\Models\Label;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;

class LabelImport implements ToCollection, WithChunkReading
{

    protected $items;

    protected $relationModel;

    public function __construct(Model $model)
    {
        $this->init();
        $this->relationModel = $model;
    }

    private function init()
    {
        $this->items = new Collection();
    }

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        $collection->each(function ($item) {
            $data = [
                'name' => $item[0],
                'task_id' => $this->relationModel->id
            ];
            $this->items->push($data);
        });
        $this->relationModel->increment('count', $this->items->count());
        if ($this->items->isNotEmpty()) {
            Label::insert($this->items->toArray());
        }
        $this->init();
    }

    public function chunkSize(): int
    {
        return 1000;
    }
}